% Put this file in the same folder with getStock_index.m

%Stockname = ['AAM';'ABT';'ACC';'AGD'];
%Indexname = 'VNINDEX';
Stockname = char(Stockname);
Indexname = char(Indexname);
% k is the number of assets
k = size(Stockname);
k = k(1);

bJS = zeros(k,2);
bmean = zeros(2,1);
betaOLS = zeros(2,k);
% alphaa = zeros(k,1);

%Get vector beta by doing OLS k times. Then calculate bmean
for i = 1:k
    %Get the return of stock and index
    [Stock Index Date PriceStock PriceIndex] = getStock_Index(Stockname(i,:),Indexname);
    rStock = PriceStock(2:end)./PriceStock(1:end-1) - 1;
    rIndex = PriceIndex(2:end)./PriceIndex(1:end-1) - 1;
    
    if i==1
        datan = x2mdate(Date,0);
    end
    if length(datan)>length(x2mdate(Date,0))
        datan = x2mdate(Date,0);
    end
    datam=datan(262:end);
end
%length(datan)
for i=1:k
    [Stock Index Date PriceStock PriceIndex] = getStock_Index(Stockname(i,:),Indexname);
    rStock = PriceStock(2:end)./PriceStock(1:end-1) - 1;
    rIndex = PriceIndex(2:end)./PriceIndex(1:end-1) - 1;
    lenStock = length(rStock)-length(datan)+2;
    rStock = rStock(lenStock:end);
    rIndex = rIndex(lenStock:end);
    %Estimation OLS
    [betaOLS(:,i) bOLS_Graph]= OLS(rStock,rIndex);
    %sizeGraph = length(bOLS_Graph)
    betaOLS_Graph(:,:,i) = bOLS_Graph(:,:);
    bmean = bmean + betaOLS(:,i);
end
bmean = bmean/k;
alpha = 1-1./k;
for i = 1:k
%     v = (1/k)*(bOLS - bmean).^2;
%     alpha = 1-(k-3)*v./(bOLS - bmean).^2

%   alphaa(i) = alpha(1,1);
    bJS(i,:) = bmean' + alpha*(betaOLS(:,i)' - bmean');
    for j = 1:length(datam)
        betaShrinkage_Graph(j,:,i) = bmean' + alpha.*(betaOLS_Graph(j,:,i) - bmean');
    end
end

%---Output to Excell
ExcelShrinkage = datam;
for i = 1:k
    temp = betaShrinkage_Graph(:,:,i);
    ExcelShrinkage=[ExcelShrinkage,temp(:,2)];
end